import React, { Component,} from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card,Descriptions,Table,Button,Image,Popconfirm,} from 'antd';
import { getDicByKey } from '@/support/common';
import PropTypes from 'prop-types';
import { routerRedux } from 'dva/router';

@connect((state: any) => ({
  menu: state.menu,
  goodMng: state.goodMng,
}))
export default class  GoodDetail extends Component<any, any> {
  static contextTypes = {
    dicData: PropTypes.any,
  };

   state = {
    current:'1',
    detail: {},
    };
  componentDidMount() {
    const { dispatch } = this.props;
    const spuId =  JSON.parse(sessionStorage.getItem('spuId') || '{}');
    if (spuId) {
      dispatch({
        type: 'goodMng/getData',
        payload: { url: '/optshop/base/goods/detail/search', spuId,},
        callback: (response: any) => {
            this.setState({
              detail: response.data
            })
        }
        },
      )
    }
  }
  getSeries=(brandId:any)=>{
    brandId &&
      this.props.dispatch({
        type: 'goodAdd/getDataWithRes',
        payload: {
          url: '/common/vehicle/getserieslist',
          brandId,
        },
        callback: (e:any) => {
          const seriesOption =  e.data?.map((e:any) => ({
              label: e.name,
              value: e.code,
            }))
          return seriesOption || []
        },
      });
  }
  getType=(brandId:any, seriesId:any)=>{
    brandId &&
      seriesId &&
      this.props.dispatch({
        type: 'goodAdd/getDataWithRes',
        payload: {
          url: '/common/vehicle/gettypelist',
          brandId,
          seriesId,
        },
        callback: e => {
           const  typeOptions = e.data.map((e:any) => ({
              label: e.name,
              value: e.code,
            }));
          return typeOptions || []
        },
      });
  }
  goBack =()=>{
    const { dispatch,location } = this.props;
    const {query:{data}}=location;
    if(data === 'orderMng'){
      dispatch(routerRedux.push({ pathname: '/goodsManager/orderMng', sourcePage: 'orderMng' }));
    }else{
        dispatch(routerRedux.push({ pathname: '/goodsManager/goodsMng', sourcePage: 'goodsMng' }));
      }
  }
  onTabChange=(key:any)=>{
    this.setState({
        current: key,
    })
  }
  formatPlatform = (data:any) => {
    let result = '';
    data?.split(',').map((d:any)=>{
      result = result + getDicByKey(this.context.dicData, 'goodsPlatform', d) + ','
    })
    return result.substring(0,result.length-1);
  }
   getContentBeforeFirstComma(str:string) {
    return str.split(',')[0];
   }
  render() {
    const status = ['未上架', '已上架', '已下架', '已作废'];
    const {detail,}=this.state;
    const columns = [
        {
          title: '序号',
          dataIndex: 'no',
          key: 'no',
          render: (text:any, record:any, index:any) => {
            return index + 1;
          },
        },
        {
          title: '附属属性名称',
          dataIndex: 'skuAttributeName',
          key: 'skuAttributeName',
        },
        {
          title: '附属属性代码',
          dataIndex: 'skuAttributeCode',
          key: 'skuAttributeCodes',
        },
        {
            title: '单位',
            dataIndex: 'unit',
            key: 'unit',
            render: (text:any) => {
              if (text) {
                return getDicByKey(this.context.dicData, 'unit', text) || text;
              } else {
                return text;
              }
            },
          },
          {
            title: '附属属性值',
            dataIndex: 'skuAttributeValue',
            key: 'skuAttributeValue',
          },
       ];
      const allTabs = [
        {
          tab: '基础信息',
          key: '1',
          component: () =>
          <div> 
            <Descriptions column={3} labelStyle={{justifyContent: 'flex-end',minWidth:110}}>
              <Descriptions.Item label="品牌" span={1}>{detail?.brandName}</Descriptions.Item>
              <Descriptions.Item label="车系" span={1}>{detail?.carSeriesName}</Descriptions.Item>
              <Descriptions.Item label="车型" span={1}>{(detail?.carTypesName&&(this.getContentBeforeFirstComma(detail?.carTypesName) == 'null' || this.getContentBeforeFirstComma(detail?.carTypesName) == '')) || !detail?.carTypesName ?  detail?.carTypes : detail?.carTypesName}</Descriptions.Item>
              <Descriptions.Item label="商品类型" span={1}>{detail?.goodsTypeName}</Descriptions.Item>
              <Descriptions.Item label="商品名称" span={1}>{detail?.spuName}</Descriptions.Item>
              <Descriptions.Item label="商品编号" span={1}>{detail?.spuId}</Descriptions.Item>
              <Descriptions.Item label="商品总量" span={1}>{detail?.spuTotalAmount}</Descriptions.Item>
              <Descriptions.Item label="有效期" span={1}>{detail?.validDate}</Descriptions.Item>
              <Descriptions.Item label="商品平台" span={1}>{this.formatPlatform(detail?.goodsPlatform)}</Descriptions.Item>
              <Descriptions.Item label="是否供应商发货" span={1}>{getDicByKey(this.context.dicData, 'ifSendBySupplier', detail?.ifSendBySupplier)}</Descriptions.Item>
              <Descriptions.Item label="支付方式" span={1}>{getDicByKey(this.context.dicData, 'payTypes', detail?.payType)}</Descriptions.Item>
              <Descriptions.Item label="是否热门" span={1}>{detail?.isHot == 1 ? '是' : '否'}</Descriptions.Item>
              <Descriptions.Item label="商品最高价格" span={1}>{detail?.goodsMaxPrice}</Descriptions.Item>
              <Descriptions.Item label="购买人群" span={1}>{getDicByKey(this.context.dicData, 'buyers', detail?.buyers)}</Descriptions.Item>
              <Descriptions.Item label="权益" span={1}>{detail?.benefits}</Descriptions.Item>
              <Descriptions.Item label="商品类目名称" span={3}>{detail?.goodsCategoryName}</Descriptions.Item>
              <Descriptions.Item label="商品状态" span={1}>{status[detail?.spuStatus] || 0 }</Descriptions.Item>
              <Descriptions.Item label="上架日期" span={1}>{detail?.saleTime}</Descriptions.Item>
              <Descriptions.Item label="下架日期" span={1}>{detail?.endTime}</Descriptions.Item>
              <Descriptions.Item label="商品描述" span={3}>{detail?.goodsDesc}</Descriptions.Item>
            </Descriptions>
            <Descriptions column={3} layout="vertical" style={{marginLeft: '20px'}}>
              <Descriptions.Item label="商品图片" span={1}>{detail?.pic &&<Image src={detail?.pic} placeholder={true} height={80} width={80} />}</Descriptions.Item>
              <Descriptions.Item label="商品图标" span={1}>{detail?.icon &&<Image src={detail?.icon}  placeholder={true} height={80} width={80} />}</Descriptions.Item>
              <Descriptions.Item label="商品附件" span={1}>
              {/* {record.goodsAttachmentName && (<Button>{record.goodsAttachmentName}</Button>)} */}
              {detail?.goodsAttachment && (<Popconfirm title="确定要下载此商品附件吗?"  onConfirm={() => window.location.href=detail?.goodsAttachment}>
                  <a>下载</a>&nbsp;&nbsp;
                </Popconfirm>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="商品二维码图片" span={3}>{detail?.goodsQrPic &&<Image src={detail?.goodsQrPic} alt="icon" placeholder={true} height={80} width={80}/>}</Descriptions.Item>
            </Descriptions>
          </div>,
          show: true,
        },
        {
          tab: '销售信息',
          key: '2',
          component: () => 
          <div> 
          <Descriptions column={3}>
            <Descriptions.Item label="商品规格" span={3}>{detail?.goodsSpecFlag == 1 ? '单规格' : '多规格'}</Descriptions.Item>
            <Descriptions.Item label="商品价格（元）" span={1}>{detail?.skus[0]?.goodsPrice}</Descriptions.Item>
            <Descriptions.Item label="商品折扣价" span={1}>{detail?.skus[0]?.discountPrice}</Descriptions.Item>
          </Descriptions>
          <Card title="附属属性" style={{marginTop: '20px'}}>
            <Table columns={columns} dataSource={detail?.skus[0]?.attributeList} pagination={false}/>
          </Card>
        </div>,
          show: true,
        },
       ];
      const {current}=this.state;
      const tabs = allTabs.filter(tab => tab.show);
      const currentTab = tabs.length ? (tabs.find(e => e.key === current)?.component()) : null;
      return (
        <Card  activeTabKey={current} tabList={tabs} title={'商品详情'} onTabChange={this.onTabChange}>
             <div style={{float:'right', marginTop:'-100px'}}>
               <Button  type="primary" onClick={()=>{this.goBack()}}>返回</Button>
             </div>
           {currentTab}
      </Card>  
    );
  }
}

